<template>
  <div>
    <!-- el-tree组件-->
    <el-tree
      ref="treeRef"
      :data="treeList"
      :props="{label:'name'}"
      :show-checkbox="true"
      default-expand-all
      :check-strictly="true"
      node-key="id"
    />
    <div style="margin-top: 20px;text-align: right">
      <el-button type="primary" @click="hAssignPer">确定</el-button>
      <el-button @click="hCancel">取消</el-button>
    </div>
  </div>
</template>

<script>
import { arr2tree } from '@/utils'
import { getPermissionList } from '@/api/permisson'
import { getRolesDetail, assignPerm } from '@/api/setting'
export default {
  name: 'AssignPermission',
  // 导入组件名
  components: {},
  // 父传子,接收变量名
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    // 这里存放数据
    return {
      treeList: []// 保存权限列表
    }
  },
  // 计算属性 类似于 data 概念
  computed: {},
  // 监听器 监控 data 中的数据变化
  watch: {},
  created() {
    this.loadPermissionList()
  },
  // 方法集合
  methods: {
    async hAssignPer() {
      try {
        const permIds = this.$refs.treeRef.getCheckedKeys()
        const res = await assignPerm({ id: this.id, permIds })
        console.log('assignPerm', res)
        // 关闭弹层
        this.$emit('close')
      } catch (err) {
        console.log('assignPerm', err)
      }
    },

    // 获取权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('getPermissionList', res)
        this.treeList = arr2tree(res.data, '0')
        const info = await getRolesDetail(this.id)
        console.log('info', info)
        // 让当前角色拥有的权限 处于选中状态
        this.$refs.treeRef.setCheckedKeys(info.data.permIds)
      } catch (err) {
        console.log('getPermissionList', err)
      }
    },
    // 取消
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>

<style scoped>
</style>
